const {
  createQuestion,
  questionInfo,
  questionDetail,
  createCollectQuestion,
  isCollect,
  deleteCollectQuestion,
  getCollectQuestion,
  hostQuestions,
} = require("../service/question.service");
class Question {
  //发布题目
  async sendQuestion(ctx, next) {
    const {
      questionTitle,
      questionAnswer,
      questionType,
      userId,
      questionPreView,
    } = ctx.request.body;
    const res = await createQuestion(
      questionTitle,
      questionAnswer,
      questionType,
      userId,
      questionPreView
    );
    ctx.body = {
      code: 0,
      message: "题目发布成功",
      data: res,
    };
  }
  //分页
  async getQuestions(ctx, next) {
    const { curentPage, pageSize, type } = JSON.parse(ctx.request.query.data);
    const res = await questionInfo(curentPage, pageSize, type);
    ctx.body = {
      code: 0,
      message: "查询题目成功",
      data: res,
    };
  }
  // 查询题目详情
  async getQuestionsDetail(ctx, next) {
    const { questionId, userId } = JSON.parse(ctx.request.query.data);
    const res = await questionDetail(questionId);
    const collect = (await isCollect(questionId, userId)) ? true : false;
    ctx.body = {
      code: 0,
      message: "查询题目详情成功",
      data: { ...res, collect },
    };
  }
  //收藏
  async collectQuestion(ctx, next) {
    const { questionId, userId } = ctx.request.body;
    const res = await createCollectQuestion(questionId, userId);
    ctx.body = {
      code: 0,
      message: "收藏成功",
      data: res,
    };
  }
  //取消收藏
  async noCollectQuestion(ctx, next) {
    const { questionId, userId } = ctx.request.body;
    const res = await deleteCollectQuestion(questionId, userId);
    ctx.body = {
      code: 0,
      message: "取消收藏成功",
      data: res,
    };
  }
  //获得所有收藏的题
  async getAllCollectQuestion(ctx, next) {
    const { userId, curentPage, pageSize } = ctx.request.body;
    const res = await getCollectQuestion(userId, curentPage, pageSize);
    ctx.body = {
      code: 0,
      message: "获得所有收藏的题",
      data: res,
    };
  }
  //热门题型
  async getHostQuestions(ctx, next) {
    try {
      const res = await hostQuestions();
      ctx.body = {
        code: 0,
        message: "热门题型获取成功",
        data: res,
      };
    } catch (error) {
      ctx.body = {
        code: -1,
        message: "热门题型获取失败",
        data: '',
      };
    }
  }
}

module.exports = new Question();
